package com.can.syn;

//不安全的买票
//线程不安全
//"苦逼的我"，"牛逼的你"，"可恶黄牛"可能会拿到同一张票，甚至在最后一张票的时候可能都会将最后一张票执行，就会有-1
public class UnsafeBuyTicket {

    public static void main(String[] args) {
        BuyTicket buyTicket = new BuyTicket();

        new Thread(buyTicket,"苦逼的我").start();
        new Thread(buyTicket,"牛逼的你").start();
        new Thread(buyTicket,"可恶黄牛").start();
    }

}

class BuyTicket implements Runnable{

    private int ticketNums = 10; //票
    private boolean flag = true; //外部停止方式

    @Override
    public void run() {
        //买票
        while (flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {
        //判断是否有票
        if(ticketNums<=0){
            flag = false;
            return;
        }

        //模拟延时
        Thread.sleep(10);
        //买票
        System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
    }
}
